package com.keepers.repair.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ServiceUtils;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import com.keepers.repair.R;
import com.keepers.repair.RepApplication;
import com.keepers.repair.adapter.FragmentAdapter;
import com.keepers.repair.aidl.IMainAidlInterface;
import com.keepers.repair.fragment.HomeFragment;
import com.keepers.repair.fragment.MsgFragment;
import com.keepers.repair.fragment.SetFragment;
import com.keepers.repair.fragment.TaskFragment;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.helper.bus.LoginExitEvent;
import com.keepers.repair.helper.bus.RxBus;
import com.keepers.repair.model.UserModel;
import com.keepers.repair.net.LogUtil;
import com.keepers.repair.service.CoreService;
import com.keepers.repair.service.KeeperService;
import com.keepers.repair.service.SocketService;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.utils.UtilsKt;
import com.keepers.repair.view.CompatViewPager;

/**
 * auth aboom
 * date 2018/10/22
 */
public class MainNewActivity extends BaseActivity {

    private HomeFragment homeFragment = new HomeFragment();
    private TaskFragment taskFragment = new TaskFragment();
    private MsgFragment  msgFragment  = new MsgFragment();
    private SetFragment  setFragment  = new SetFragment();

    public  IMainAidlInterface iMainAidlInterface;
    private ServiceConnection  connection;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.e("MainNewActivity onCreate");
        UserModel loginUserInfo = SpHelper.getLoginUserInfo();
        String s = JSONObject.toJSONString(loginUserInfo);
        LogUtil.e("loginUserInfo = " + s);
        setContentView(R.layout.activity_main_new);
        transparencyBar();
        initNetworkReceiver();
        startCoreService();// 启动CoreService
//        startSocketService();// 启动KeeperService
        startSocketService();
//        acquirePowerManagerWakeLock();// 获取PowerManagerWakeLock
        initViews();
//        getClient();


//        Intent intent = new Intent(this, SocketService.class);
//        if (iMainAidlInterface == null) xi
//            bindService(intent, connection, Context.BIND_AUTO_CREATE);
//        }
//        JobSchedulerManager jobSchedulerManager = JobSchedulerManager.getJobSchedulerInstance();
//        jobSchedulerManager.startJobScheduler();

        rxHelper.pend(RxBus.getDefault().toObservable(LoginExitEvent.class)
                .subscribe(loginExitEvent -> {
                    LogUtil.e("退出登录...关闭socket连接");
                    if (iMainAidlInterface != null) {
                        try {
                            iMainAidlInterface.closeTcp();
                            if (loginExitEvent.isReloadSocket) {
                                iMainAidlInterface.initTcp();
                            }
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }));
    }

    private void startSocketService() {
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                LogUtil.e("_SPI_SERVICE onServiceConnected()");
                iMainAidlInterface = IMainAidlInterface.Stub.asInterface(service);
                initViews();
                if (ServiceUtils.isServiceRunning(SocketService.class.getName())) {
                    try {
                        iMainAidlInterface.initTcp();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                LogUtil.e("_SPI_SERVICE onServiceDisconnected()");
            }
        };
        Intent startIntent = new Intent(this, SocketService.class);
        startService(startIntent);
        Intent bindIntent = new Intent(this, SocketService.class);
        bindIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);
    }

    private void stopSocketService() {
        LogUtil.e("_SPI_SERVICE stopKeeperService()-S-");
        if (connection != null) {
            Intent stopIntent = new Intent(this, SocketService.class);
            stopService(stopIntent);
            unbindService(connection);
        }
        LogUtil.e("_SPI_SERVICE stopKeeperService()-E-");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.e("MainNewActivity onNewIntent");
    }

    /**
     * 检查权限
     */
    private void getClient() {
        //可以连接
        RepApplication.getApp().startConnectSocketServer();
    }

    // ===============防止CPU休眠造成计时不准确 Start===============================
    // PARTIAL_WAKE_LOCK CPU Off Screen:Off Keyboard:Off
    private PowerManager.WakeLock powerManagerWakeLock;

    public void acquirePowerManagerWakeLock() {
        LogUtil.e("acquirePowerManagerWakeLock()PowerManagerWakeLock:" + powerManagerWakeLock);
        if (null != powerManagerWakeLock) {
            powerManagerWakeLock.release();
            powerManagerWakeLock = null;
        }
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (pm != null) {
            powerManagerWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PATROLCLIENT");
            powerManagerWakeLock.acquire();
        }
    }

    private void startKeeperService() {
        LogUtil.e("_SPI_SERVICE startSocketService()-S-");
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                LogUtil.e("_SPI_SERVICE onServiceConnected()");
                KeeperService.KeeperBinder keeperBinder = (KeeperService.KeeperBinder) service;
                keeperBinder.startHeartBeat();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                LogUtil.e("_SPI_SERVICE onServiceDisconnected()");
            }
        };
        Intent startIntent = new Intent(this, KeeperService.class);
        startService(startIntent);
        Intent bindIntent = new Intent(this, KeeperService.class);
        bindIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);
        LogUtil.e("_SPI_SERVICE startSocketService()-E-");
    }

    private void stopKeeperService() {
        LogUtil.e("_SPI_SERVICE stopKeeperService()-S-");
        if (connection != null) {
            Intent stopIntent = new Intent(this, KeeperService.class);
            stopService(stopIntent);
            unbindService(connection);
        }
        LogUtil.e("_SPI_SERVICE stopKeeperService()-E-");
    }

    private void startCoreService() {
        if (!ServiceUtils.isServiceRunning(CoreService.class)) {
            CoreService.startCoreService(this);
        }
    }

//    private ServiceConnection connection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            iMainAidlInterface = IMainAidlInterface.Stub.asInterface(service);
//            initViews();
//            if (com.blankj.utilcode.util.ServiceUtils.isServiceRunning(SocketService.class.getName())) {
//                try {
//                    iMainAidlInterface.initTcp();
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//        }
//    };


    private void initViews() {
        CompatViewPager compatViewPager = f(R.id.main_content);
        BottomNavigationViewEx bottomNavigationViewEx = f(R.id.main_tab);
        bottomNavigationViewEx.enableShiftingMode(false);
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentAdapter fragmentAdapter = new FragmentAdapter(supportFragmentManager, homeFragment, taskFragment, msgFragment, setFragment);
        compatViewPager.setAdapter(fragmentAdapter);
        bottomNavigationViewEx.setupWithViewPager(compatViewPager);
        bottomNavigationViewEx.setOnNavigationItemSelectedListener(item -> true);
    }

    private BroadcastReceiver netWorkStateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean networkConnected = UtilsKt.isNetworkConnected();
            AlertToast.show("网络发生变化");
            homeFragment.networkCall(networkConnected);
        }
    };

    private void initNetworkReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.e("MainNewActivity onDestroy");
        unbindService(connection);
        unregisterReceiver(netWorkStateReceiver);
//        stopSocketService();
//        stopKeeperService();
    }
}
